// Transmission 页面交互逻辑

// 全局变量
let tasksData = [];
let filteredTasks = [];
let currentPage = 1;
const tasksPerPage = 20;

// DOM 元素变量声明
let tasksTableBody;
let searchInput;
let refreshBtn;
let addTaskBtn;
let addTaskModal;
let closeModalBtn;
let cancelAddBtn;
let addTaskForm;
let prevPageBtn;
let nextPageBtn;
let pageInfo;
let startItem;
let endItem;
let totalItems;
let totalTasks;
let downloadingTasks;
let pausedTasks;
let completedTasks;

// 初始化页面
function initPage() {
    // 获取DOM元素
    tasksTableBody = document.getElementById('tasks-table-body');
    searchInput = document.getElementById('search-input');
    refreshBtn = document.getElementById('refresh-btn');
    addTaskBtn = document.getElementById('add-task-btn');
    addTaskModal = document.getElementById('add-task-modal');
    closeModalBtn = document.getElementById('close-modal-btn');
    cancelAddBtn = document.getElementById('cancel-add-btn');
    addTaskForm = document.getElementById('add-task-form');
    prevPageBtn = document.getElementById('prev-page');
    nextPageBtn = document.getElementById('next-page');
    pageInfo = document.getElementById('page-info');
    startItem = document.getElementById('start-item');
    endItem = document.getElementById('end-item');
    totalItems = document.getElementById('total-items');
    totalTasks = document.getElementById('total-tasks');
    downloadingTasks = document.getElementById('downloading-tasks');
    pausedTasks = document.getElementById('paused-tasks');
    completedTasks = document.getElementById('completed-tasks');

    // 绑定事件监听器
    if (refreshBtn) refreshBtn.addEventListener('click', refreshTasks);
    if (addTaskBtn) addTaskBtn.addEventListener('click', openAddTaskModal);
    if (closeModalBtn) closeModalBtn.addEventListener('click', closeAddTaskModal);
    if (cancelAddBtn) cancelAddBtn.addEventListener('click', closeAddTaskModal);
    if (addTaskForm) addTaskForm.addEventListener('submit', handleAddTask);
    if (searchInput) searchInput.addEventListener('input', filterTasks);
    if (prevPageBtn) prevPageBtn.addEventListener('click', goToPrevPage);
    if (nextPageBtn) nextPageBtn.addEventListener('click', goToNextPage);
    
    // 点击模态框外部关闭
    addTaskModal.addEventListener('click', function(e) {
        if (e.target === addTaskModal) {
            closeAddTaskModal();
        }
    });
    
    // 页面加载后立即刷新任务列表，确保点击页面能显示内容
    if (refreshBtn && typeof refreshBtn.click === 'function') {
        // 使用requestAnimationFrame确保DOM已经完全渲染
        requestAnimationFrame(() => {
            refreshBtn.click();
        });
    } else {
        // 备用方案：直接调用loadTasks函数
        loadTasks();
    }
}

// 加载任务列表
function loadTasks() {
    showLoadingState();
    
    fetch('/api/transmission/tasks')
        .then(response => {
            if (!response.ok) {
                throw new Error(`请求失败：${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                tasksData = data.data || [];
                filteredTasks = [...tasksData];
                updateTaskTable();
                updateTaskStats();
                updatePagination();
            } else {
                showError(data.message || '加载任务失败');
            }
        })
        .catch(error => {
            showError(`加载任务失败：${error.message}`);
        })
        .finally(() => {
            hideLoadingState();
        });
}

// 刷新任务列表
function refreshTasks() {
    currentPage = 1;
    loadTasks();
}

// 打开添加任务模态框
function openAddTaskModal() {
    addTaskForm.reset();
    addTaskModal.classList.remove('hidden');
}

// 关闭添加任务模态框
function closeAddTaskModal() {
    addTaskModal.classList.add('hidden');
}

// 处理添加任务
function handleAddTask(e) {
    e.preventDefault();
    
    const torrentUrl = document.getElementById('torrent-url').value;
    const savePath = document.getElementById('save-path').value;
    const startPaused = document.querySelector('input[name="start_paused"]').checked;
    
    const confirmAddBtn = document.getElementById('confirm-add-btn');
    const originalText = confirmAddBtn.innerHTML;
    
    confirmAddBtn.disabled = true;
    confirmAddBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 添加中...';
    
    fetch('/api/transmission/add-task', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            torrent_url: torrentUrl,
            save_path: savePath,
            start_paused: startPaused
        })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`请求失败：${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            showNotification('任务添加成功', 'success');
            closeAddTaskModal();
            loadTasks(); // 重新加载任务列表
        } else {
            showNotification(`添加任务失败：${data.message || '未知错误'}`, 'error');
        }
    })
    .catch(error => {
        showNotification(`添加任务失败：${error.message}`, 'error');
    })
    .finally(() => {
        confirmAddBtn.disabled = false;
        confirmAddBtn.innerHTML = originalText;
    });
}

// 筛选任务
function filterTasks() {
    const searchTerm = searchInput.value.toLowerCase().trim();
    
    if (!searchTerm) {
        filteredTasks = [...tasksData];
    } else {
        filteredTasks = tasksData.filter(task => 
            task.name.toLowerCase().includes(searchTerm)
        );
    }
    
    currentPage = 1;
    updateTaskTable();
    updateTaskStats();
    updatePagination();
}

// 更新任务表格
function updateTaskTable() {
    tasksTableBody.innerHTML = '';
    
    if (filteredTasks.length === 0) {
        tasksTableBody.innerHTML = `
            <tr class="text-center">
                <td colspan="8" class="px-6 py-12 text-gray-500">
                    <div class="flex flex-col items-center justify-center">
                        <i class="fa fa-folder-open-o text-4xl mb-4 text-gray-400"></i>
                        <p>暂无任务</p>
                    </div>
                </td>
            </tr>
        `;
        return;
    }
    
    const startIndex = (currentPage - 1) * tasksPerPage;
    const endIndex = Math.min(startIndex + tasksPerPage, filteredTasks.length);
    const pageTasks = filteredTasks.slice(startIndex, endIndex);
    
    pageTasks.forEach(task => {
        const row = document.createElement('tr');
        row.className = 'hover:bg-gray-50 transition-colors';
        
        // 状态样式
        let statusClass = '';
        let statusText = task.status;
        
        if (task.status === 'downloading') {
            statusClass = 'text-green-600';
            statusText = '下载中';
        } else if (task.status === 'seeding') {
            statusClass = 'text-blue-600';
            statusText = '做种中';
        } else if (task.status === 'stopped') {
            statusClass = 'text-yellow-600';
            statusText = '已暂停';
        } else if (task.status === 'seeding_wait') {
            statusClass = 'text-purple-600';
            statusText = '等待做种';
        } else if (task.status === 'unknown') {
            statusClass = 'text-gray-600';
            statusText = '未知状态';
        } else {
            // 默认状态处理
            statusClass = 'text-gray-600';
            statusText = '未知状态';
        }
        
        row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap max-w-xs">
                <div class="text-sm font-medium text-gray-900 truncate" title="${task.name}">${task.name}</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900">${formatSize(task.total_size)}</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <div class="w-full bg-gray-200 rounded-full h-2.5">
                    <div class="bg-blue-600 h-2.5 rounded-full" style="width: ${Math.min(task.progress / 100, 100).toFixed(1)}%">
                    </div>
                </div>
                <div class="text-xs text-gray-500 mt-1">${(task.progress / 100).toFixed(1)}%</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 ${statusClass}">
                    ${statusText}
                </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900">${formatSpeed(task.rate_download)}</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900">${formatSpeed(task.rate_upload)}</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900">${formatSize(task.size_when_done * task.progress / 100)}</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900">${formatSize(task.uploaded_ever)}</div>
            </td>
        `;
        
        tasksTableBody.appendChild(row);
    });
}

// 更新任务统计信息
function updateTaskStats() {
    const total = filteredTasks.length;
    totalTasks.textContent = total;
}

// 更新分页
function updatePagination() {
    const totalPages = Math.ceil(filteredTasks.length / tasksPerPage);
    
    // 更新页码信息
    pageInfo.textContent = `第 ${currentPage} 页，共 ${totalPages} 页`;
    
    // 更新前后页按钮状态
    prevPageBtn.disabled = currentPage === 1;
    nextPageBtn.disabled = currentPage === totalPages;
    
    if (prevPageBtn.disabled) {
        prevPageBtn.classList.add('opacity-50', 'cursor-not-allowed');
    } else {
        prevPageBtn.classList.remove('opacity-50', 'cursor-not-allowed');
    }
    
    if (nextPageBtn.disabled) {
        nextPageBtn.classList.add('opacity-50', 'cursor-not-allowed');
    } else {
        nextPageBtn.classList.remove('opacity-50', 'cursor-not-allowed');
    }
    
    // 更新显示范围
    if (filteredTasks.length === 0) {
        startItem.textContent = '0';
        endItem.textContent = '0';
        totalItems.textContent = '0';
    } else {
        const start = (currentPage - 1) * tasksPerPage + 1;
        const end = Math.min(currentPage * tasksPerPage, filteredTasks.length);
        
        startItem.textContent = start;
        endItem.textContent = end;
        totalItems.textContent = filteredTasks.length;
    }
}

// 上一页
function goToPrevPage() {
    if (currentPage > 1) {
        currentPage--;
        updateTaskTable();
        updatePagination();
        scrollToTop();
    }
}

// 下一页
function goToNextPage() {
    const totalPages = Math.ceil(filteredTasks.length / tasksPerPage);
    if (currentPage < totalPages) {
        currentPage++;
        updateTaskTable();
        updatePagination();
        scrollToTop();
    }
}

// 显示加载状态
function showLoadingState() {
    tasksTableBody.innerHTML = `
        <tr class="text-center">
            <td colspan="10" class="px-6 py-12 text-gray-500">
                <div class="flex flex-col items-center justify-center">
                    <i class="fa fa-spinner fa-spin text-4xl mb-4 text-blue-500"></i>
                    <p>正在加载任务列表...</p>
                </div>
            </td>
        </tr>
    `;
}

// 隐藏加载状态
function hideLoadingState() {
    // 加载完成后由updateTaskTable处理
}

// 显示错误信息
function showError(message) {
    tasksTableBody.innerHTML = `
        <tr class="text-center">
            <td colspan="10" class="px-6 py-12 text-gray-500">
                <div class="flex flex-col items-center justify-center">
                    <i class="fa fa-exclamation-circle text-4xl mb-4 text-red-500"></i>
                    <p>${message}</p>
                </div>
            </td>
        </tr>
    `;
}

// 格式化文件大小
function formatSize(bytes) {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 格式化速度
function formatSpeed(bytesPerSecond) {
    if (bytesPerSecond === 0) return '0 B/s';
    
    const k = 1024;
    const sizes = ['B/s', 'KB/s', 'MB/s', 'GB/s'];
    const i = Math.floor(Math.log(bytesPerSecond) / Math.log(k));
    
    return parseFloat((bytesPerSecond / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 滚动到顶部
function scrollToTop() {
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `fixed top-4 right-4 px-4 py-3 rounded-md shadow-lg transform transition-all duration-300 z-50 max-w-md`;
    
    // 设置通知样式
    switch(type) {
        case 'success':
            notification.classList.add('bg-green-100', 'text-green-800', 'border-l-4', 'border-green-500');
            break;
        case 'error':
            notification.classList.add('bg-red-100', 'text-red-800', 'border-l-4', 'border-red-500');
            break;
        default:
            notification.classList.add('bg-blue-100', 'text-blue-800', 'border-l-4', 'border-blue-500');
    }
    
    // 设置通知内容
    notification.innerHTML = `
        <div class="flex">
            <div class="flex-shrink-0">
                <i class="fa fa-${type === 'success' ? 'check' : type === 'error' ? 'times' : 'info'} text-2xl"></i>
            </div>
            <div class="ml-3">
                <p class="text-sm font-medium">${message}</p>
            </div>
            <button class="ml-auto -mx-1.5 -my-1.5 bg-white bg-opacity-20 text-gray-500 hover:text-gray-700 rounded-full p-1 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                <span class="sr-only">关闭</span>
                <i class="fa fa-times"></i>
            </button>
        </div>
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.classList.add('translate-y-0', 'opacity-100');
        notification.classList.remove('translate-y-[-20px]', 'opacity-0');
    }, 10);
    
    // 自动关闭
    const closeBtn = notification.querySelector('button');
    closeBtn.addEventListener('click', () => {
        closeNotification(notification);
    });
    
    setTimeout(() => {
        closeNotification(notification);
    }, 5000);
}

// 关闭通知
function closeNotification(notification) {
    notification.classList.add('opacity-0');
    setTimeout(() => {
        notification.remove();
    }, 300);
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', initPage);